# coding=utf-8

from . import base
from .component import Component
from .component_manager import get_version
import time

## 实现一个组件，需要写如下几个方法：
class Venus(Component):

    ## 依赖的组件，返回类型为 string 数组，例如 return ["docker"]，表示该组件依赖的其他组件
    def dependencies(self):
        if base.is_windows():
            return ["docker", "redis", "mqtt_server"]
        else:
            return ["docker", "redis", "mqtt_server"]



    ## 检测安装状态，返回true或者false，用于显示是否已经安装该组件
    def check(self):
        if base.is_windows():
            return base.check_service("venus_server");
        else:
            return base.check_docker_container("venus_server");



    ## 检测运行状态，返回true或者false，表示该组件是否正在运行
    def status(self):
        if base.is_windows():
            return base.is_service_running("venus_server");
        else:
            return base.is_container_running("venus_server");




    ## 安装组件 
    def install(self, rVersion : str = None):
        print("install venus")
        if rVersion is None:
            print("请使用 -r 指定要安装的镜像 tag ，例如 en install venus -r 1.0.0.S15")
            return False

        EN_PATH = base.get_env("EN_PATH")

        if base.is_dir(f"{cm.EN_DATA}/venus"):
            base.delete_dir(f"{cm.EN_DATA}/venus")
        
        base.copy_files(f"{EN_PATH}/linux/gonsin/venus/template", f"{cm.EN_DATA}/venus")
        f = open(file = f"{cm.EN_DATA}/venus/template/docker-compose.yml", mode = 'r', encoding='utf8')
        content = f.read()
        content = content.replace('##rVersion##', rVersion)
        f.close()
        with open(file = f"{cm.EN_DATA}/venus/template/docker-compose.yml", mode='w', encoding='utf8') as f:
            f.write(content)
        ## TODO 先不管windows的情况
        base.copy_files(f"{EN_PATH}/linux/gonsin/venus/template/images", "/home/gonsin/venus/files/")
        base.cmd_in_dir(f"{cm.EN_DATA}/venus/template", "./install_venus.sh")
        return True
            
            
    def backup(self) -> None:
        ''' 备份venus镜像
        
        Parameters
        ----------
        
        
        Returns
        -------
        None
        
        '''
        ## 移除上一次备份
        base.cmd("docker", ["image", "rm", "venus_server_backup", "-f"], True)
        base.cmd("docker", ["image", "rm", "venus_mysql_backup", "-f"], True)
        base.cmd("docker", ["image", "rm", "venus_web_backup", "-f"], True)

        ## 创建新的备份
        backup_time = time.strftime('%Y-%m-%d %H:%M-%S', time.gmtime())
        base.cmd("docker", ["commit", "-m", f"\"备份时间 {backup_time}\"", "venus_server", "venus_server_backup"])
        base.cmd("docker", ["commit", "-m", f"\"备份时间 {backup_time}\"", "venus_mysql", "venus_mysql_backup"])
        base.cmd("docker", ["commit", "-m", f"\"备份时间 {backup_time}\"", "venus_web", "venus_web_backup"])

        pass


    def restore(self) -> None:
        ''' 从备份中恢复
        
        Parameters
        ----------
        
        
        Returns
        -------
        None
        
        '''
        
        pass


    ## 更新组件
    def update(self, rVersion : str = None):

        # self.uninstall_notDelete();
        # ## 因为install 和 update内容相同，所以直接调用
        # self.install(rVersion);
        current_version = get_version("venus")
        print("current version is : " + str(current_version))
        if rVersion is None:
           # rVersion = 'latest'
           if current_version is not None:
               rVersion = current_version

        # 备份会务容器
        # self.backup();

        EN_PATH = base.get_env("EN_PATH")

        if base.is_dir(f"{cm.EN_DATA}/venus"):
            base.delete_dir(f"{cm.EN_DATA}/venus")
        base.copy_files(f"{EN_PATH}/linux/gonsin/venus/template", f"{cm.EN_DATA}/venus")

        # 先 docker-compose build 拉取镜像
        f = open(file = f"{cm.EN_DATA}/venus/template/docker-compose.yml", mode = 'r', encoding='utf8')
        content = f.read()
        f.close()
        content = content.replace('##rVersion##', rVersion)
        with open(file = f"{cm.EN_DATA}/venus/template/docker-compose.yml", mode='w', encoding='utf8') as f:
            f.write(content)
        ## TODO 先不管windows的情况
        # 如果是和安装时的版本相同 则 直接运行更新脚本(因为镜像标签相同无法先拉取镜像)
        # 如果和安装的版本不同 则先拉取新版本的镜像
        if rVersion == current_version :
            print("perform the same version update")
            base.cmd_in_dir(f"{cm.EN_DATA}/venus/template", "./update_venus.sh")
        else:
            print("perform different version update")
            # 拉取镜像
            base.cmd_in_dir(f"{cm.EN_DATA}/venus/template", "sudo docker-compose pull")
            print("All updated files have been downloaded successfully ")
            print("Please wait for the program to automatically update ")
            print("This will take approximately 3-5 minutes ")
            # docker-compose 版本改回旧版本 以停止旧服务
            content = content.replace(rVersion,current_version)
            with open(file = f"{cm.EN_DATA}/venus/template/docker-compose.yml", mode='w', encoding='utf8') as f:
                f.write(content)
            base.cmd_in_dir(f"{cm.EN_DATA}/venus/template", "sudo docker-compose down")
            # docker-compose 版本改回新版本 以启动服务
            content = content.replace(current_version,rVersion)
            with open(file = f"{cm.EN_DATA}/venus/template/docker-compose.yml", mode='w', encoding='utf8') as f:
                f.write(content)
            base.cmd_in_dir(f"{cm.EN_DATA}/venus/template", "sudo docker-compose up -d")
        return True

    def uninstall_not_delete(self):
        if base.check_docker_container('venus_server'):
            base.remove_docker_container('venus_server')
        if base.check_docker_container('venus_web'):
            base.remove_docker_container('venus_web')
        if base.check_docker_container('venus_mysql'):
            base.remove_docker_container('venus_mysql')
        # 清空所有缓存
        base.cmd("docker", ["system", "prune", "-f" , "-a"])

    ## 卸载
    def uninstall(self):
        if base.check_docker_container('venus_server'):
            base.remove_docker_container('venus_server')
        if base.check_docker_container('venus_web'):
            base.remove_docker_container('venus_web')
        if base.check_docker_container('venus_mysql'):
            base.remove_docker_container('venus_mysql')

        # 清空所有缓存
        base.cmd("docker", ["system", "prune", "-f" , "-a"])
        base.cmd("rm -rf /home/gonsin/venus/*")

from . import component_manager as cm
cm.ALL_COMPONENTS['venus'] = Venus()